package com.corpgovernment.permission.service;

import com.corpgovernment.permission.entity.db.MbRolePermission;
import com.corpgovernment.permission.mapper.RolePermissionMapper;
import com.corpgovernment.redis.handler.RedisHandler;
import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class RolePermissionService implements RelationSrv<Long, Long> {
    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    @Autowired
    private RedisHandler redisHandler;
    public static final String ROLE_REDIS_PREFIX = "roleId:";
    @Override
    public void clearLeft(Set<Long> roleIds) {
        Example e = new Example(MbRolePermission.class);
        List<Long> c = roleIds.stream().filter(Objects::nonNull).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(c)) {
            return;
        }
        e.createCriteria().andIn("roleId", c);
        rolePermissionMapper.deleteByExample(e);
    }

    @Override
    public void clearRight(Set<Long> permissionIds) {
        Example e = new Example(MbRolePermission.class);
        List<Long> c = permissionIds.stream().filter(Objects::nonNull).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(c)) {
            return;
        }
        e.createCriteria().andIn("permissionId", c);
        rolePermissionMapper.deleteByExample(e);
    }

    @Override
    public void batchAssociate(Set<Long> roleIds, Set<Long> permissionIds) {
        List<Relation<Long, Long>> relations = map(roleIds, permissionIds);
        relations.stream().map(r -> {
            MbRolePermission rp = new MbRolePermission();
            rp.setPermissionId(r.getRight());
            rp.setRoleId(r.getLeft());
            return rp;
        }).forEach(rolePermissionMapper::insertSelective);
    }

    /**
     * 缓存新的权限
     */
    public void refreshRolePermissionCache(Long roleId, List<Long> mbRolePermissionList){
        if (roleId != null){
            redisHandler.setValue(ROLE_REDIS_PREFIX + roleId, mbRolePermissionList, 60*60*24*15);
        }

    }

    public List<MbRolePermission> listRolePermission(Long roleId) {
        return rolePermissionMapper.listByRoleId(roleId);
    }

}
